# Importing Data
KUWAIT <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Iran/KUWAIT.xlsx")

# Checking the Imported Data
View(KUWAIT)

# Creating Time Series Data
KUWAIT_ts <- ts(KUWAIT, start=c(2008,01), end=c(2017,12), frequency=12)

# Viewing and Checking the Created Time Series Data
KUWAIT_ts
sum(is.na(KUWAIT_ts))
library(forecast)
KUWAIT_ts <- tsclean(KUWAIT_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(KUWAIT_ts)
plot(aggregate(KUWAIT_ts,FUN=mean))

# Decomposing
KUWAIT_ts_decomp <- decompose(KUWAIT_ts)
plot(KUWAIT_ts_decomp)

# Testing for Stationarity
acf(KUWAIT_ts, lag.max=20)
pacf(KUWAIT_ts, lag.max=20)

# To see any seasonal effect
boxplot(KUWAIT_ts~cycle(KUWAIT_ts))

# To remove trend effect
KUWAIT_ts_diff <- diff(KUWAIT_ts)
plot(KUWAIT_ts_diff)

# To remove variance effect
KUWAIT_ts_log <- log(KUWAIT_ts)
plot(KUWAIT_ts_log)

# To remove both (Trend and Variance) effects
KUWAIT_ts_both <- diff(log(KUWAIT_ts))
plot(KUWAIT_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(KUWAIT_ts, lag.max=20)
acf(log(KUWAIT_ts), lag.max=20)
acf(diff(KUWAIT_ts), lag.max=20)
acf(diff(log(KUWAIT_ts)), lag.max=20)
pacf(KUWAIT_ts, lag.max=20)
pacf(log(KUWAIT_ts), lag.max=20)
pacf(diff(KUWAIT_ts), lag.max=20)
pacf(diff(log(KUWAIT_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
KUWAIT_ts_model <- auto.arima(KUWAIT_ts)
KUWAIT_ts_model
KUWAIT_ts_model <- auto.arima(KUWAIT_ts, ic="aic", trace = TRUE)
KUWAIT_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(KUWAIT_ts_model$resid)
acf(KUWAIT_ts_model$residuals, main='ACF Residual')
pacf(KUWAIT_ts_model$residuals, main='ACF Residual')
Box.test(KUWAIT_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
KUWAIT_ts_forecast <- forecast (KUWAIT_ts_model, level=c(95), h=276)
plot(KUWAIT_ts_forecast)
KUWAIT_ts_forecast             



write.table(KUWAIT_ts_forecast, file="Kuwait_TSA.csv", sep=",")
